import { Component, OnInit, Input, Output, forwardRef, EventEmitter, } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { CommonService } from '../../../../services-common/common.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';

@Component({
  selector: 'storage-select-bom',
  templateUrl: './storage-select-bom.component.html',
  styleUrls: ['./storage-select-bom.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => StorageSelectBomComponent),
      multi: true
    }
  ]
})
export class StorageSelectBomComponent implements OnInit {

  @Input() goodsId!: Number | String;
  @Output() onBomConfirm = new EventEmitter();

  isBomVisible = false;
  bomNumber: string | number = '';
  subDisabled = false;
  onChange: any = () => {};

  constructor(
    private msg: NzMessageService,
    private commonService: CommonService,
    private storageCommonService: StorageCommonService
  ) { }

  ngOnInit(): void {
  }

  writeValue(val: any) {
    if (val) {
      this.bomNumber = '';
    }
    this.isBomVisible = val;
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    // this.onTouched = fn;
  }

  // submit data
  async sumitBom(type: number) {
    if (this.commonService.isEmpty(this.bomNumber)) {
      this.msg.warning('请输入采购倍数');
      return
    }

    let params = {
      id: this.goodsId,
      boomNumber: this.bomNumber,
      type: type
    }
    
    this.subDisabled = true;
    const mbId = this.msg.loading('处理中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.storageCommonService.getBomList(params);
    this.msg.remove(mbId);
    this.subDisabled = false;

    if (code === 0) {
      this.onBomConfirm.emit(data);
      this.isBomVisible = false;
      this.onChange(false);
    } else {
      this.msg.error(message);
    }
  }
}
